package xwbank.jmeter5.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketClientUtil {
    public String sendXmlMsg(String xmlStr, String ipAddress, String portStr){
        String serverIP = ipAddress;
        int port = Integer.parseInt(portStr);
        try (Socket client = new Socket(serverIP,port);
             OutputStream out = client.getOutputStream()) {
            byte[] b = xmlStr.getBytes("UTF-8");
            out.write(int2Bytes8(b.length));
            out.write(b);
            InputStream in = client.getInputStream();
            byte[] rb = new byte[8];
            in.read(rb);
            int len = Integer.parseInt(new String(rb,"UTF-8"));
            rb = new byte[len];
            in.read(rb);
            String returnData = new String(rb,0,len,"UTF-8");
            return returnData;
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] int2Bytes8(int num) {
        StringBuffer sb = new StringBuffer(String.valueOf(num));
        int length = 8 - sb.length();
        for(int i=0; i<length; i++){
            sb.insert(0,'0');
        }
        return sb.toString().getBytes();
    }
}
